package com.lm56.web.sys.controller;

import com.lm56.web.CommonService;
import com.lm56.web.network.domain.ShippingType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by Kelvin Yeung on 2016/12/5.
 */
@Component //需要注入commonService 所以把这里注册成组件
public class ShippingTypesCollectionEditor extends CustomCollectionEditor {

    @Autowired
    CommonService commonService;

    public ShippingTypesCollectionEditor() {
        super(List.class);
    }

    public ShippingTypesCollectionEditor(boolean nullAsEmptyCollection) {
        super(List.class, nullAsEmptyCollection);
    }

    @Override
    protected Object convertElement(Object element)
    {
        List<ShippingType> shippingTypes=new ArrayList<ShippingType>();
        if(element instanceof String && !element.equals("")){
            //From the JSP 'element' will be a String
            try{
                String[] ids = ((String) element).split(",");
                for(String  id:ids){
                    Long typeId = Long.parseLong(id);
                    ShippingType shippingType = commonService.loadShippingTypeById(typeId);
                    if(shippingType != null){
                        shippingTypes.add(shippingType);
                    }

                }
            }
            catch (NumberFormatException e) {
                System.out.println("Element was " + element);
                e.printStackTrace();
                throw new RuntimeException("输入的运输方式代码不正确");
            }
        }
        else if(element instanceof Long) {
            //From the database 'element' will be a Long
            ShippingType shippingType = commonService.loadShippingTypeById((Long) element);
            if(shippingType != null){
                shippingTypes.add(shippingType);
            }
        }

        return shippingTypes;
    }
}
